package com.beanu.arad.view;

import android.content.Context;
import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.R;
import com.beanu.arad.base.my_base.AddressBean;
import com.beanu.arad.utils.ToastUtils;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by  on 2018/4/11.
 */

public class AddressPickerView extends RelativeLayout {
    private Context mContext;
    private TabLayout tabLayout;
    private ImageView iv_close;
    private RecyclerView recyclerView;
    private AddressAdapter adapter;
    private AddressBean addressBean;
    private AddressBean.AddressItemBean mSelectProvice;
    private AddressBean.AddressItemBean mSelectCity;
    private AddressBean.AddressItemBean mSelectDistrict;
    private List<AddressBean.AddressItemBean> addressItemBeans;

    private int mSelectProvicePosition = 0; //选中 省份 位置
    private int mSelectCityPosition = 0;//选中 城市  位置
    private int mSelectDistrictPosition = 0;//选中 区县  位置

    private int defauletSureCanClickColor = Color.parseColor("#bbff0000");
    private int defauletUnselectClickColor = Color.parseColor("#66000000");

    private OnAddressPickerSureListener mOnAddressPickerSureListener;

    public AddressPickerView(Context context) {
        super(context);
        initView(context);
    }

    public AddressPickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public AddressPickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        addressItemBeans = new ArrayList<>();
        View view = inflate(mContext, R.layout.address_picker_view, this);
        tabLayout = view.findViewById(R.id.tabLayout);
        iv_close = view.findViewById(R.id.iv_close);
        recyclerView = view.findViewById(R.id.recyclerView);
        tabLayout.addTab(tabLayout.newTab().setText("请选择"));
        tabLayout.addOnTabSelectedListener(onTabSelectedListener);

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new AddressAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                initData();
            }
        });
        iv_close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnAddressPickerSureListener.OnClick(view);
            }
        });
    }

    private void initData() {
        StringBuffer js = new StringBuffer();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(mContext.getAssets().open("address.json")));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                js.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        addressBean = new Gson().fromJson(js.toString(), AddressBean.class);
        if (addressBean != null) {
            addressItemBeans.clear();
            addressItemBeans.addAll(addressBean.getProvince());
            adapter.notifyDataSetChanged();
        }
    }

    TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            addressItemBeans.clear();
            switch (tab.getPosition()) {
                case 0:

                    addressItemBeans.addAll(addressBean.getProvince());
                    adapter.notifyDataSetChanged();
                    recyclerView.smoothScrollToPosition(mSelectProvicePosition);
                    break;

                case 1:
                    // 点到城市的时候要判断有没有选择省份
                    if (mSelectProvice != null) {
                        for (AddressBean.AddressItemBean addressItemBean : addressBean.getCity()) {
                            if (addressItemBean.getP().equals(mSelectProvice.getI())) {
                                addressItemBeans.add(addressItemBean);
                            }
                        }
                    } else {
                        ToastUtils.showShort("请您先选择省份");
//                        Toast.makeText(mContext, "请您先选择省份", Toast.LENGTH_SHORT).show();
                    }
                    adapter.notifyDataSetChanged();
                    recyclerView.smoothScrollToPosition(mSelectCityPosition);
                    break;
                case 2:
                    // 点到区的时候要判断有没有选择省份与城市
                    if (mSelectProvice != null && mSelectCity != null) {
                        for (AddressBean.AddressItemBean addressItemBean : addressBean.getDistrict()) {
                            if (addressItemBean.getP().equals(mSelectCity.getI())) {
                                addressItemBeans.add(addressItemBean);

                            }
                        }
                    } else {
                        ToastUtils.showShort("请您先选择省份与城市");
                    }
                    adapter.notifyDataSetChanged();
                    recyclerView.smoothScrollToPosition(mSelectDistrictPosition);
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.ViewHolder> {


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_tab_title, parent, false));
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            final int tabSelectPosition = tabLayout.getSelectedTabPosition();
            holder.tv_tab_name.setText(addressItemBeans.get(position).getN());
            switch (tabSelectPosition) {
                case 0:
                    if (addressItemBeans.get(position) != null &&
                            mSelectProvice != null &&
                            addressItemBeans.get(position).getI().equals(mSelectProvice.getI())) {
                        holder.tv_tab_name.setTextColor(defauletSureCanClickColor);
                        holder.iv_check.setImageResource(R.mipmap.ic_check);
                    }else {
                        holder.tv_tab_name.setTextColor(defauletUnselectClickColor);
                        holder.iv_check.setImageResource(0);
                    }
                    break;
                case 1:
                    if (addressItemBeans.get(position) != null &&
                            mSelectCity != null &&
                            addressItemBeans.get(position).getI().equals(mSelectCity.getI())) {
                        holder.tv_tab_name.setTextColor(defauletSureCanClickColor);
                        holder.iv_check.setImageResource(R.mipmap.ic_check);
                    }else {
                        holder.tv_tab_name.setTextColor(defauletUnselectClickColor);
                        holder.iv_check.setImageResource(0);
                    }
                    break;
                case 2:
                    if (addressItemBeans.get(position) != null &&
                            mSelectDistrict != null &&
                            addressItemBeans.get(position).getI().equals(mSelectDistrict.getI())) {
                        holder.tv_tab_name.setTextColor(defauletSureCanClickColor);
                        holder.iv_check.setImageResource(R.mipmap.ic_check);
                    }else {
                        holder.tv_tab_name.setTextColor(defauletUnselectClickColor);
                        holder.iv_check.setImageResource(0);
                    }
                    break;
            }
            holder.tv_tab_name.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    {
                        // 点击 分类别
                        switch (tabSelectPosition) {
                            case 0:
                                mSelectProvice = addressItemBeans.get(position);
                                // 清空后面两个的数据
                                mSelectCity = null;
                                mSelectDistrict = null;
                                mSelectCityPosition = 0;
                                mSelectDistrictPosition = 0;
                                if (tabLayout.getTabCount() <= 2) {
                                    tabLayout.addTab(tabLayout.newTab());
                                    tabLayout.getTabAt(1).setText("请选择");
                                }else {
                                    tabLayout.removeTabAt(2);
                                    tabLayout.getTabAt(1).setText("请选择");
                                }
//                            mTabLayout.getTabAt(2);
                                // 设置这个对应的标题
                                tabLayout.getTabAt(0).setText(mSelectProvice.getN());
                                // 跳到下一个选择
                                tabLayout.getTabAt(1).select();
                                mSelectProvicePosition = position;
                                break;
                            case 1:
                                mSelectCity = addressItemBeans.get(position);
                                // 清空后面一个的数据
                                mSelectDistrict = null;
                                mSelectDistrictPosition = 0;
                                if (tabLayout.getTabCount() <= 3) {
                                    tabLayout.addTab(tabLayout.newTab());
                                    tabLayout.getTabAt(2).setText("请选择");
                                }
                                // 设置这个对应的标题
                                tabLayout.getTabAt(1).setText(mSelectCity.getN());
                                // 跳到下一个选择
                                tabLayout.getTabAt(2).select();
                                mSelectCityPosition = position;
                                break;
                            case 2:
                                mSelectDistrict = addressItemBeans.get(position);
                                // 没了，选完了，这个时候可以点确定了
                                tabLayout.getTabAt(2).setText(mSelectDistrict.getN());
                                notifyDataSetChanged();
                                // 确定按钮变亮
                                sure();
                                break;
                        }
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return addressItemBeans.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_tab_name;
            ImageView iv_check;

            public ViewHolder(View itemView) {
                super(itemView);
                tv_tab_name = itemView.findViewById(R.id.tv_tab_name);
                iv_check = itemView.findViewById(R.id.iv_check);
            }
        }
    }

    private void sure() {
        //   回调接口
        if (mOnAddressPickerSureListener != null) {
            mOnAddressPickerSureListener.onSureClick(mSelectProvice.getN() + " " + mSelectCity.getN()+ " " + mSelectDistrict.getN() + " ",mSelectProvice.getN() + " " ,mSelectCity.getN() + " " ,mSelectDistrict.getN()
                   );
        }
    }

    /**
     * 点确定回调这个接口
     */
    public interface OnAddressPickerSureListener {
        void onSureClick(String address, String province, String city, String district);

        void OnClick(View view);
    }

    public void setOnAddressPickerSure(OnAddressPickerSureListener listener) {
        this.mOnAddressPickerSureListener = listener;
    }

    public void setOnClickListener( OnAddressPickerSureListener l) {
        this.mOnAddressPickerSureListener = l;
    }
}

